import BigNumber from "bignumber.js";

import { isValid, toString } from "@lib/com.verify";

/** 将一个任意数字（经常是金额元）放大整数倍，并保证最后的数字是整数
 * @muti 乘数，如 3366*100 中的 100
 * @integerValue 将会舍弃小数位
 */
export function toMultiplySafe(mess: any, multi: number = 1) {
  return new BigNumber(toString(mess, "0")).times(new BigNumber(multi)).integerValue(BigNumber.ROUND_DOWN).toNumber();
}

/** 不会丢失精度的除法
 * @divisor 除数，如 3366/100 中的 100
 * @bits 默认作除法后保留-2位小数-然后直接舍弃其他小数
 */
export function toDivideSafe(mess: any, divisor: number = 1, bits: number = 2) {
  const value = new BigNumber(toString(mess, "0")).dividedBy(new BigNumber(divisor)).toFixed(bits, BigNumber.ROUND_DOWN);
  return Number(value);
}

/** 默认除以-100-然后转化成带有逗号的会计字符串
 * @digit 保留n位小数
 */
export function toViewAmount(
  amount?: any,
  divider = 100,
  options?: {
    digit: number;
  },
) {
  const digit = isValid(options?.digit) ? options!.digit : 2;
  return toDivideSafe(amount, divider, digit)
    .toLocaleString("zh-CN", {
      style: "currency",
      currency: "CNY",
      minimumFractionDigits: digit,
      maximumFractionDigits: digit,
    })
    .replace(/¥/g, "");
}

/** 获取中文金额 */
export function toChineseMoney(n: number): string {
  const fraction = ["角", "分"];
  const digit = ["零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖"];
  const unit = [
    ["元", "万", "亿"],
    ["", "拾", "佰", "仟"],
  ];

  const head = n < 0 ? "欠" : "";
  n = Math.abs(n);

  let s = "";

  // 处理小数部分（角和分）
  for (let i = 0; i < fraction.length; i++) {
    const decimalPart = Math.floor(n * Math.pow(10, i + 1)) % 10;
    s += (digit[decimalPart] + fraction[i]).replace(/零./, "");
  }
  s = s || "整"; // 如果没有小数部分，显示“整”
  n = Math.floor(n); // 取整数部分

  // 处理整数部分
  for (let i = 0; i < unit[0].length && n > 0; i++) {
    let p = "";
    for (let j = 0; j < unit[1].length && n > 0; j++) {
      p = digit[n % 10] + unit[1][j] + p;
      n = Math.floor(n / 10);
    }
    s = p.replace(/(零.)*零$/, "").replace(/^$/, "零") + unit[0][i] + s;
  }

  return (
    head +
    s
      .replace(/(零.)*零元/, "元")
      .replace(/(零.)+/g, "零")
      .replace(/^整$/, "零元整")
  );
}
